package com.example.demo.Service;

import com.example.demo.exception.FileStorageException;
import com.example.demo.model.Movie;
import com.example.demo.repository.MovieRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

@Service
public class FileStorageService {

    @Autowired
    private MovieRepository movieRepository;

    @Value("${file.upload-dir}")
    private String uploadDir;

    @Value("${file.virtual-file-prefix}")
    private String virtualFilePrefix;

    private final Path fileStorageLocation;

    public FileStorageService(@Value("${file.upload-dir}") String uploadDir, @Value("${file.virtual-file-prefix}") String virtualFilePrefix) {
        System.out.println("Upload directory: " + uploadDir); // 添加日志输出
        if (uploadDir == null || uploadDir.isEmpty()) {
            throw new IllegalArgumentException("上传目录配置未设置");
        }

        this.uploadDir = uploadDir;
        this.virtualFilePrefix = virtualFilePrefix;
        this.fileStorageLocation = Paths.get(uploadDir).toAbsolutePath().normalize();
        try {
            Files.createDirectories(this.fileStorageLocation);
            System.out.println("Directory created: " + this.fileStorageLocation); // 添加日志输出
        } catch (Exception ex) {
            throw new FileStorageException("无法创建用于存储上传文件的目录。", ex);
        }
    }

    public String storeFile(MultipartFile file, Long movieId) {
        String fileName = StringUtils.cleanPath(file.getOriginalFilename());
        try {
            if (fileName.contains("..")) {
                throw new FileStorageException("文件名包含非法路径序列：" + fileName);
            }

            // 获取电影对象
            Movie movie = movieRepository.findById(movieId)
                    .orElseThrow(() -> new FileStorageException("电影未找到"));

            // 将文件保存到文件系统
            Path targetLocation = this.fileStorageLocation.resolve(fileName);
            Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);

            // 设置电影的海报 URL
            String filePath = virtualFilePrefix + "/" + fileName;
            movie.setPosterUrl(filePath);

            // 保存电影对象到数据库
            movieRepository.save(movie);

            return fileName;
        } catch (IOException ex) {
            throw new FileStorageException("无法存储文件 " + fileName + "，请重试。", ex);
        }
    }

    public Resource getPoster(String posterUrl) {
        try {
            // 从虚拟文件前缀中提取文件名
            String fileName = posterUrl.substring(virtualFilePrefix.length() + 1);
            Path filePath = this.fileStorageLocation.resolve(fileName).normalize();

            // 检查文件是否存在
            if (!Files.exists(filePath)) {
                throw new FileStorageException("文件不存在: " + fileName);
            }

            // 返回文件资源
            return new ByteArrayResource(Files.readAllBytes(filePath));
        } catch (IOException ex) {
            throw new FileStorageException("无法读取文件: " + posterUrl, ex);
        }
    }
}